package com.ms.controller;

import com.ms.entity.Manager;
import com.ms.entity.PlaceApplication;
import com.ms.entity.QuaApplication;
import com.ms.entity.Volunteer;
import com.ms.service.inter.ManagerService;
import com.ms.service.inter.PlaceApplicationService;
import com.ms.service.inter.QuaApplicationService;
import com.ms.service.inter.VolunteerService;
import com.ms.utils.SimpleTokenUtils;
import com.ms.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/manager") // 正确设置基础路径
@CrossOrigin(origins = "*")
public class ManagerController {

    @Autowired // 注入 Service 实例
    private ManagerService managerService;
    
    @Autowired
    private PlaceApplicationService placeApplicationService;
    
    @Autowired
    private QuaApplicationService quaApplicationService;
    
    @Autowired
    private VolunteerService volunteerService;



    //功能一：管理员登录，并注册token，保持登录状态
    //测试路径：localhost:8080/manager/login?account=110&password=110
    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String account, @RequestParam String password) {
        return managerService.login(account, password, null);
    }


    // 功能二：管理员退出登录
    //测试路径：localhost:8080/manager/logout
    @PostMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 清除上下文信息
            UserContext.remove();
            result.put("success", true);
            result.put("message", "退出成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }


    //功能三；管理员修改密码
    //测试路径：localhost:8080/manager/password?oldPassword=110&newPassword=111
    @PutMapping("/password")
    public Map<String, Object> changePassword(HttpServletRequest request,
                                             @RequestBody Map<String, String> passwordData) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return result;
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("message", "无权限操作");
                return result;
            }

            Manager currentUser = (Manager) userObj;
            Integer managerId = currentUser.getMaId();
            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");

            boolean success = managerService.changePassword(managerId, oldPassword, newPassword);
            result.put("success", success);
            result.put("message", success ? "密码修改成功" : "密码修改失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }



    // 功能四：主管理员创建普通管理员账号，账号不能与已有账号重复
    //测试路径：localhost:8080/manager/create
    // 请求体：
    //{
    //  "maName": "一只有功的猴子",
    //  "maAccount": "123456",
    //  "maPssword": "123456"
    //}
    @PostMapping("/create")
    public Map<String, Object> createManager(HttpServletRequest request,@RequestBody Manager manager)
    {

        Map<String, Object> result = new HashMap<>();

        // 1. 验证当前用户是否为主管理员
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            result.put("success", false);
            result.put("msg", "未登录");
            return result;
        }

        /*Manager currentUser = SimpleTokenUtils.getUserByToken(token);*/
        Object currentUserObj = SimpleTokenUtils.getUserByToken(token);
        Manager currentUser = null;
        if (currentUserObj instanceof Manager) {
            currentUser = (Manager) currentUserObj;
        }

        if (currentUser == null || !currentUser.getMaIsMain()) {
            result.put("success", false);
            result.put("msg", "权限不足，只有主管理员可以创建账号");
            return result;
        }

        // 2. 验证账号是否已存在
        Manager existingManager = managerService.getManagerByAccount(manager.getMaAccount());
        if (existingManager != null) {
            result.put("success", false);
            result.put("msg", "账号已存在");
            return result;
        }

        // 3. 设置默认值
        manager.setMaIsMain(false); // 新创建的管理员默认不是主管理员
        manager.setMaIsUsing(true); // 默认在线状态为使用中

        // 4. 保存管理员信息
        boolean success = managerService.save(manager);
        if (success) {
            result.put("success", true);
            result.put("msg", "创建成功");
            result.put("newManager", manager.toString());
        } else {
            result.put("success", false);
            result.put("msg", "创建失败");
        }

        return result;
    }



    //功能五：获取当前管理员信息
    //测试路径：localhost:8080/manager/info
    @GetMapping("/info")
    public Map<String, Object> getManagerInfo(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return result;
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("message", "无权限操作");
                return result;
            }

            Manager currentUser = (Manager) userObj;
            Integer managerId = currentUser.getMaId();
            Manager manager = managerService.getManagerInfo(managerId);

            result.put("success", true);
            result.put("manager", manager);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }



    //功能六：主管理员查看所有非主管理员账号列表
    //测试路径：localhost:8080/manager/getNOMainList
    @GetMapping("/getNOMainList")
    public Map<String, Object> listNonMainManagers(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }

            Manager currentUser = (Manager) userObj;
            // 检查是否为主管理员
            if (!currentUser.getMaIsMain()) {
                result.put("success", false);
                result.put("msg", "权限不足，只有主管理员可以查看");
                return result;
            }

            // 查询所有非主管理员账号
            QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ma_isMain", false);
            List<Manager> managers = managerService.list(queryWrapper);

            result.put("success", true);
            result.put("data", managers);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "查询失败：" + e.getMessage());
        }

        return result;
    }



    //功能七；主管理员控制非主管理员账号的启用/停用状态
    @PostMapping("/ChangeMAStatus")
    public Map<String, Object> toggleManagerStatus(HttpServletRequest request,
                                                   @RequestParam Integer managerId,
                                                   @RequestParam Boolean isUsing) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }

            Manager currentUser = (Manager) userObj;
            // 检查是否为主管理员
            if (!currentUser.getMaIsMain()) {
                result.put("success", false);
                result.put("msg", "权限不足，只有主管理员可以操作");
                return result;
            }

            // 检查目标管理员是否存在且不是主管理员
            Manager targetManager = managerService.getById(managerId);
            if (targetManager == null) {
                result.put("success", false);
                result.put("msg", "管理员不存在");
                return result;
            }

            if (targetManager.getMaIsMain()) {
                result.put("success", false);
                result.put("msg", "不能操作主管理员账号");
                return result;
            }

            // 更新管理员状态
            boolean success = managerService.updateManagerOnlineStatus(managerId, isUsing);
            if (success) {
                result.put("success", true);
                result.put("msg", isUsing ? "账号已启用" : "账号已停用");
            } else {
                result.put("success", false);
                result.put("msg", "操作失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "操作失败：" + e.getMessage());
        }

        return result;
    }


    //功能八；；主管理员更新普通管理员信息
    @PostMapping("/updateManager")
    public Map<String, Object> updateManagerInfo(HttpServletRequest request, @RequestBody Manager manager) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }

            Manager currentUser = (Manager) userObj;
            // 检查是否为主管理员
            if (!currentUser.getMaIsMain()) {
                result.put("success", false);
                result.put("msg", "权限不足，只有主管理员可以修改管理员信息");
                return result;
            }

            // 检查要更新的管理员是否存在
            Manager existingManager = managerService.getById(manager.getMaId());
            if (existingManager == null) {
                result.put("success", false);
                result.put("msg", "管理员不存在");
                return result;
            }

            // 检查是否试图将普通管理员修改为主管理员
            if (manager.getMaIsMain() != null && manager.getMaIsMain() && !existingManager.getMaIsMain()) {
                result.put("success", false);
                result.put("msg", "不能将普通管理员设置为主管理员");
                return result;
            }

            // 更新管理员信息
            boolean success = managerService.updateManagerInfo(manager);
            if (success) {
                result.put("success", true);
                result.put("msg", "管理员信息更新成功");
            } else {
                result.put("success", false);
                result.put("msg", "管理员信息更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "操作失败：" + e.getMessage());
        }

        return result;
    }


    //功能九；管理员审批场地申请
    @PostMapping("/approvePlaceApplication")
    public Map<String, Object> approvePlaceApplication(HttpServletRequest request,
                                                       @RequestBody PlaceApplication application) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }
            
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }
            
            // 审批场地申请
            boolean success = placeApplicationService.approvePlaceApplication(application);
            if (success) {
                result.put("success", true);
                result.put("msg", "审批成功");
            } else {
                result.put("success", false);
                result.put("msg", "审批失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "审批失败：" + e.getMessage());
        }
        
        return result;
    }
    

    //功能十；获取所有场地申请记录（供管理员使用）
    @GetMapping("/getAllPlaceApplications")
    public Map<String, Object> getAllPlaceApplications(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }
            
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }
            
            // 查询所有场地申请记录，按申请时间倒序排列
            List<PlaceApplication> applications = placeApplicationService.list();
            result.put("success", true);
            result.put("data", applications);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "查询失败：" + e.getMessage());
        }
        
        return result;
    }


    //功能十一：管理员查看所有资格申请（举办方申请举办比赛的资格）
    @GetMapping("/getAllQuaApplications")
    public Map<String, Object> getAllQuaApplications(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }
            
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }
            
            // 查询所有资格申请记录，按申请状态和时间排序
            List<QuaApplication> applications = quaApplicationService.getAllApplyStatusOrdered();
            result.put("success", true);
            result.put("data", applications);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "查询失败：" + e.getMessage());
        }
        
        return result;
    }


    //功能十二：管理员审批资格申请（举办方申请举办比赛的资格）
    @PostMapping("/approveQuaApplication")
    public Map<String, Object> approveQuaApplication(HttpServletRequest request,
                                                   @RequestBody QuaApplication application) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }
            
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }
            
            // 审批资格申请
            boolean success = quaApplicationService.feedbackApplyResult(application);
            if (success) {
                result.put("success", true);
                result.put("msg", "审批成功");
            } else {
                result.put("success", false);
                result.put("msg", "审批失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "审批失败：" + e.getMessage());
        }
        
        return result;
    }


    //功能十三：管理员查看所有志愿者申请
    @GetMapping("/getAllVolunteerApplications")
    public Map<String, Object> getAllVolunteerApplications(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }
            
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }
            
            // 查询所有志愿者申请记录，按申请状态和时间排序
            List<Volunteer> applications = volunteerService.findAll();
            result.put("success", true);
            result.put("data", applications);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "查询失败：" + e.getMessage());
        }
        
        return result;
    }


    //功能十四：管理员审批志愿者申请
    @PostMapping("/approveVolunteerApplication")
    public Map<String, Object> approveVolunteerApplication(HttpServletRequest request,
                                                         @RequestBody Volunteer application) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从token中获取当前登录的管理员信息
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("msg", "未登录");
                return result;
            }
            
            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof Manager)) {
                result.put("success", false);
                result.put("msg", "无权限操作");
                return result;
            }
            
            // 检查申请是否存在
            Volunteer existingApplication = volunteerService.findById(application.getVolunteerID());
            if (existingApplication == null) {
                result.put("success", false);
                result.put("msg", "申请记录不存在");
                return result;
            }
            
            // 更新申请状态和审核意见
            existingApplication.setStatus(application.getStatus());
            existingApplication.setReviewNotes(application.getReviewNotes());
            
            boolean success = volunteerService.update(existingApplication);
            if (success) {
                result.put("success", true);
                result.put("msg", "审批成功");
            } else {
                result.put("success", false);
                result.put("msg", "审批失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "审批失败：" + e.getMessage());
        }
        
        return result;
    }

}